document.addEventListener("DOMContentLoaded", function() {
    const chatBox = document.getElementById("chat-box");
    const chatInput = document.getElementById("chat-input");
    const sendBtn = document.getElementById("send-btn");

    // 发送消息
    function sendMessage() {
        const userMessage = chatInput.value.trim();
        if (userMessage === "") return;

        // 用户消息
        appendMessage("user", userMessage);
        chatInput.value = "";

        // 调用 OpenAI 接口
        fetch("/chat", {
            method: "POST",
            headers: { "Content-Type": "application/json" },
            body: JSON.stringify({ message: userMessage })
        })
        .then(response => response.json())
        .then(data => {
            appendMessage("ai", data.reply);
        })
        .catch(error => console.error("Error:", error));
    }

    // 添加消息到聊天框
    function appendMessage(sender, text) {
        const messageDiv = document.createElement("div");
        messageDiv.classList.add("message", sender === "user" ? "user-message" : "ai-message");

        const avatar = document.createElement("img");
        avatar.src = sender === "user" ? "user-avatar.png" : "ai-avatar.png";
        avatar.classList.add("avatar");

        const bubble = document.createElement("div");
        bubble.classList.add("bubble", sender === "user" ? "user-bubble" : "ai-bubble");
        bubble.textContent = text;

        if (sender === "user") {
            messageDiv.appendChild(bubble);
            messageDiv.appendChild(avatar);
        } else {
            messageDiv.appendChild(avatar);
            messageDiv.appendChild(bubble);
        }

        chatBox.appendChild(messageDiv);
        chatBox.scrollTop = chatBox.scrollHeight;
    }

    // 发送按钮监听
    sendBtn.addEventListener("click", sendMessage);

    // 回车键发送
    chatInput.addEventListener("keypress", function(event) {
        if (event.key === "Enter") {
            sendMessage();
        }
    });
});
